@import AVFoundation;
#import "dfhgwhruebvhrheycurvereciprocalViewController.h"
@interface dfhgwhruebvhrheycurvereciprocalViewController ()<AVCapturePhotoCaptureDelegate>
@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureDeviceInput *input;
@property (nonatomic, strong) AVCapturePhotoOutput *photoOutput;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
@end
@implementation dfhgwhruebvhrheycurvereciprocalViewController {
	UIView *preView;
	UILabel *tipsText;
	UIButton *takeBtn;
	void(^_finish)(UIImage *photo);
}
- (void)viewDidLoad {
    [super viewDidLoad];
	[self loadUI];
	[self configureCamera];
}
- (void)loadUI {
	[self configBackIcon:@"dhgfywegwygeydwcurvereciprocal"];
	tipsText = [[UILabel alloc] init];
	tipsText.font = [UIFont regular:14];
	tipsText.textColor = [UIColor whiteColor];
	tipsText.text = self.tipsString.length ? self.tipsString : @"Take shot your own defined ID card properly";
	[self.view addSubview:tipsText];
	preView = [[UIView alloc] init];
	preView.backgroundColor = [UIColor whiteColor];
	preView.layer.cornerRadius = 10;
	[self.view addSubview:preView];
	takeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	takeBtn.tag = 100;
	takeBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
	[takeBtn setImage:[UIImage imageNamed:@"ppp_home_identity_camera_take"] forState:UIControlStateNormal];
	[self.view addSubview:takeBtn];
	[takeBtn addTarget:self action:@selector(cameraBtnsAction) forControlEvents:UIControlEventTouchUpInside];
}
- (void)configureCamera {
	AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
	NSError *error = nil;
	self.input = [[AVCaptureDeviceInput alloc] initWithDevice:device error:&error];
	if (error) {
		NSLog(@"相机初始化失败");
		return;
	}
	self.photoOutput = [[AVCapturePhotoOutput alloc] init];
	self.session = [[AVCaptureSession alloc] init];
	if ([self.session canSetSessionPreset:AVCaptureSessionPresetPhoto]) {
		[self.session setSessionPreset:AVCaptureSessionPresetPhoto];
	}
	if([self.session canAddInput:self.input]) {
		[self.session addInput:self.input];
	}
	if ([self.session canAddOutput:self.photoOutput]) {
		[self.session addOutput:self.photoOutput];
	}
	self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
	self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
	self.previewLayer.cornerRadius = 10;
	self.previewLayer.connection.videoOrientation = AVCaptureVideoOrientationPortrait;
	[preView.layer insertSublayer:self.previewLayer atIndex:0];
	dispatch_async(dispatch_get_global_queue(0, 0), ^{
		[self.session startRunning];
	});
}
- (void)cameraFinish:(void(^)(UIImage *photo))finish {
	_finish = finish;
}
- (void)cameraBtnsAction {
	AVCaptureConnection *connection = [self.photoOutput connectionWithMediaType:AVMediaTypeVideo];
	if(!connection) {
		return [self.view show:@"take photo failed!"];
	}
	if (connection.supportsVideoOrientation) {
		connection.videoOrientation = self.previewLayer.connection.videoOrientation;
	}
	AVCapturePhotoSettings *settings = [AVCapturePhotoSettings photoSettings];
	if ([self.photoOutput.availablePhotoCodecTypes containsObject:AVVideoCodecTypeJPEG]) {
		NSDictionary *format = @{AVVideoCodecKey: AVVideoCodecTypeJPEG};
		settings = [AVCapturePhotoSettings photoSettingsWithFormat:format];
	}
	if (settings.highResolutionPhotoEnabled == YES) {	
		settings.highResolutionPhotoEnabled = YES;
	}
	settings.photoQualityPrioritization = AVCapturePhotoQualityPrioritizationBalanced;
	[self.photoOutput capturePhotoWithSettings:settings delegate:self];
}
- (void)backAction {
	[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)viewDidLayoutSubviews {
	[super viewDidLayoutSubviews];
	[tipsText mas_makeConstraints:^(MASConstraintMaker *make) {
		make.height.mas_equalTo(25);
		make.centerX.equalTo(self.view);
		make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(15);
	}];
	[preView mas_makeConstraints:^(MASConstraintMaker *make) {
		make.top.equalTo(tipsText.mas_bottom).offset(28);
		make.left.equalTo(self.view).offset(13);
		make.centerX.equalTo(self.view);
		make.height.mas_equalTo(300);
	}];
	[takeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
		make.centerX.equalTo(self.view);
		make.size.mas_equalTo(CGSizeMake(60, 60));
		make.top.equalTo(preView.mas_bottom).offset(52);
	}];
	self.previewLayer.frame = preView.bounds;
}
#pragma mark ============= AVCapturePhotoCaptureDelegate ==========
- (void)captureOutput:(AVCapturePhotoOutput *)output willCapturePhotoForResolvedSettings:(AVCaptureResolvedPhotoSettings *)resolvedSettings {
	AudioServicesDisposeSystemSoundID(1108);
}
- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error {
	[self.session stopRunning];
	UIImage *originImage = [[UIImage alloc] initWithData:[photo fileDataRepresentation]];
	originImage = [originImage fixOrientation];
	CGFloat width = self.previewLayer.frame.size.width;
	CGFloat height = self.previewLayer.frame.size.height;
	CGFloat scale = [[UIScreen mainScreen] scale];
	CGSize size = CGSizeMake(width*scale, height*scale);
	UIImage *scaledImage = [originImage resizedImageWithContentMode:UIViewContentModeScaleAspectFill size:size interpolationQuality:kCGInterpolationHigh];
	CGRect cropFrame = CGRectMake((scaledImage.size.width - size.width) * 0.5, (scaledImage.size.height - size.height) * 0.5, size.width, size.height);
	UIImage *croppedImage = [scaledImage croppedImage:cropFrame];
	if(_finish) {
		if(croppedImage) {
			_finish(croppedImage);
		}
		[self backAction];
	}
}
@end
